#include "Stdafx.h"
#include "Community.h"

using namespace SNMP;

Community::Community(void){}

Community::Community(HSNMP_SESSION hSession, HSNMP_CONTEXT hContext)
{
	this->m_hContext = hContext;
	this->m_hSession = hSession;
}

Community::~Community(void)
{
	SnmpFreeContext(this->m_hContext);
}

void Community::Clear(void)
{
	SnmpFreeContext(this->m_hContext);
	//SNMPAPI_STATUS status = SnmpFreeContext(this->m_hContext);
	/*
	if(status == SNMPAPI_FAILURE)
	{
		status =  SnmpGetLastError(NULL);
		SNMPManager::ErrorManage(status);
	}
	*/
}

void Community::CreateContextHandle(HSNMP_SESSION hSession, System::String^ context)
{
	unsigned char* community = (unsigned char*)(void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(context);
	smiOCTETS contextName;
	contextName.len = context->Length;
	contextName.ptr = community;

	this->m_hContext = hSession;
	this->m_hContext = SnmpStrToContext(hSession, &contextName);
	System::Runtime::InteropServices::Marshal::FreeHGlobal((System::IntPtr)community);
	
	//smiOCTETS contextName = Helper::ToOctets(context);
	//this->m_hContext = SnmpStrToContext(hSession, &contextName);
	if(this->m_hContext ==  SNMPAPI_FAILURE)
	{
		SNMPAPI_STATUS status = SnmpGetLastError(hSession);
		SNMPManager::ErrorManage(status);
	}
}

System::String^ Community::ContextToString(HSNMP_CONTEXT context, HSNMP_SESSION hSession)
{
	smiOCTETS outValue;
	SNMPAPI_STATUS status = SnmpContextToStr(context,  &outValue);
	if(status ==  SNMPAPI_FAILURE)
	{
		SNMPAPI_STATUS status = SnmpGetLastError(hSession);
		SNMPManager::ErrorManage(status);
	}
	//unsigned char* temp = outValue.ptr;
	System::Text::StringBuilder^ sbTemp = gcnew System::Text::StringBuilder();
	for(unsigned int i = 0; i < outValue.len; i++)
	{
		//System::Char chrValue = (System::Char)outValue.ptr[i];
		sbTemp->Append((System::Char)outValue.ptr[i]);
	}
	return sbTemp->ToString();
}